import axios from 'axios';
import { Message } from 'element-ui';
import { getToken } from '@/utils/auth';
import errorCode from '@/utils/errorCode';
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
let baseURL = process.env.VUE_APP_BASE_API;
if (window.AudioConfig.base.url.length > 0) {
  baseURL = window.AudioConfig.base.url[Math.floor(Math.random() * window.ScreenConfig.base.url.length)];
}
const service = axios.create({
  baseURL,
  timeout: Number(window.AudioConfig.base.timeout)
});

// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof (value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
  const code = res.data.code || 200;
  const msg = errorCode[code] || res.data.msg || errorCode['default'];
  if (code == 401) {
    location.href = '/login';
  } else if (code != 200) {
    // Message({
    //   message: msg,
    //   type: 'error'
    // });
    return res.data;
    return Promise.reject(new Error(msg));
  } else {
    return res.data;
  }
},
  error => {
    let { message } = error;
    if (message == "Network Error") {
      message = "网络故障，请检查网络";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      if (message.includes("401")) {
        Message.closeAll();
        Message({
          message: '登录状态已过期，请您重新登录',
          type: 'error'
        });
        location.href = '/login';
        return Promise.reject();
      }
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    //只保留最近的一个报错信息
    Message.closeAll();
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
)
export default service
